import { defineStore } from 'pinia';
import { store } from '@/store';
import { itemMapQuery } from '@/api/system/dict';
import { ItemMap } from '@/api/system/model/dictModel';

interface DictCache {
  dictMapList: ItemMap[];
}

export const useDictStore = defineStore({
  id: 'app-dict',
  state: (): DictCache => ({
    dictMapList: [],
  }),
  getters: {
    getDictMapList(state): ItemMap {
      return state.dictMapList;
    },
  },
  actions: {
    getDict(_key: string) {
      if (_key == null && _key == '') {
        return null;
      }
      try {
        for (let i = 0; i < this.dictMapList.length; i++) {
          if (this.dictMapList[i].key == _key) {
            return this.dictMapList[i].value;
          }
        }
      } catch (e) {
        return null;
      }
    },
    setDict(_key: string, _value: any) {
      if (_key !== null && _key !== '') {
        this.dictMapList.push({
          key: _key,
          value: _value,
        });
      }
    },
    // 删除字典
    removeDict(_key) {
      let bln = false;
      try {
        for (let i = 0; i < this.dictMapList.length; i++) {
          if (this.dictMapList[i].key == _key) {
            this.dictMapList.splice(i, 1);
            return true;
          }
        }
      } catch (e) {
        bln = false;
      }
      return bln;
    },
    // 清空字典
    cleanDict() {
      this.dictMapList = [];
    },
    async resetDict() {
      this.cleanDict();
      const data = await itemMapQuery();
      for (const key in data) {
        this.setDict(key, data[key]);
      }
      /*this.dictMapList = data;*/
    },
  },
});

export function useDictStoreWithOut() {
  return useDictStore(store);
}
